/*
 * Copyright (C) 2013 TopCoder Inc., All Rights Reserved.
 */
package cn.itcast.dao.impl;

import java.util.Date;


import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.hibernate.hql.ast.tree.RestrictableStatement;

import cn.itcast.hibernate.HibernateUtil;
import cn.itcast.hibernate.dao.UserDao;
import cn.itcast.hibernate.domain.User;

/**
 * @author TCSASSEMBLER
 * @version 1.0 ()
 * @since 1.0
 */
public class UserDaoHibernateImpl implements UserDao {

	/* (non-Javadoc)
	 * @see cn.itcast.hibernate.dao.UserDao#findUserById(int)
	 */
	@Override
	public User findUserById(int id) {
		// TODO Auto-generated method stub
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			User user = (User)s.get(User.class, id);
			return user;
		} finally {
			if(s != null)
				s.close();
		}
	
	}
	
	public User findUserByName2(String name) {
		// TODO Auto-generated method stub
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			String hql = "from User as user where user.name = :n";
			Query q = s.createQuery(hql);
			q.setString("n", name);
			User user = (User)q.uniqueResult();
			return user;
		} finally {
			if(s != null)
				s.close();
		}
	
	}

	/* (non-Javadoc)
	 * @see cn.itcast.hibernate.dao.UserDao#findUserByName(java.lang.String)
	 */
	@Override
	public User findUserByName(String name) {
		Session s = null;
		try {
			s = HibernateUtil.getSession();
			Criteria c = s.createCriteria(User.class);
			c.add(Restrictions.eq("name", name));
			User user = (User)c.uniqueResult();
			return user;
		} finally {
			if(s != null)
				s.close();
		}
	}

	/* (non-Javadoc)
	 * @see cn.itcast.hibernate.dao.UserDao#remove(cn.itcast.hibernate.domain.User)
	 */
	@Override
	public void remove(User user) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.delete(user);
			tx.commit();
		} finally {
			if(s != null)
				s.close();
		}
	}

	/* (non-Javadoc)
	 * @see cn.itcast.hibernate.dao.UserDao#saveUser(cn.itcast.hibernate.domain.User)
	 */
	@Override
	public void saveUser(User user) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.save(user);
			tx.commit();
		} finally {
			if(s != null)
				s.close();
		}
	}

	/* (non-Javadoc)
	 * @see cn.itcast.hibernate.dao.UserDao#updateUser(cn.itcast.hibernate.domain.User)
	 */
	@Override
	public void updateUser(User user) {
		Session s = null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.update(user);
			tx.commit();
		} finally {
			if(s != null)
				s.close();
		}
	}



}
